# apps/imports/models.py
from django.db import models
from django.utils.translation import gettext_lazy as _

from apps.tenants.models import Tenant
from apps.users.models import QBUser


class ImportLog(models.Model):
    # 上传文件名
    file_name = models.CharField(
        max_length=255,
        verbose_name=_("上传文件名")
    )

    # 文件大小，单位：字节
    file_size = models.BigIntegerField(
        verbose_name=_("文件大小（字节）")
    )

    # 总记录数
    total_count = models.IntegerField(
        default=0,
        verbose_name=_("总记录数")
    )

    # 成功导入数
    success_count = models.IntegerField(
        default=0,
        verbose_name=_("成功导入数")
    )

    # 失败数
    fail_count = models.IntegerField(
        default=0,
        verbose_name=_("失败数")
    )

    # 错误详情（可存储 JSON 或纯文本）
    error_log = models.TextField(
        null=True,
        blank=True,
        verbose_name=_("错误详情（JSON或文本）")
    )

    # 操作人（外键关联用户表，级联删除）
    importer = models.ForeignKey(
        QBUser,
        on_delete=models.CASCADE,
        verbose_name=_("操作人")
    )

    # 导入类型：手动 / 定时
    IMPORT_TYPE_CHOICES = [
        ('manual', _('手动')),
        ('scheduled', _('定时')),
    ]
    import_type = models.CharField(
        max_length=20,
        choices=IMPORT_TYPE_CHOICES,
        default='manual',
        verbose_name=_("导入类型")
    )

    # 导入状态：等待、处理中、完成、失败
    STATUS_CHOICES = [
        ('pending', _('等待')),
        ('processing', _('处理中')),
        ('completed', _('完成')),
        ('failed', _('失败')),
    ]
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        verbose_name=_("状态")
    )

    # 开始时间
    started_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name=_("开始时间")
    )

    # 完成时间
    completed_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name=_("完成时间")
    )

    # 创建时间（自动设置为创建时的时间）
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name=_("创建时间")
    )

    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, db_index=True, verbose_name="租户")

    class Meta:
        db_table = 'qb_import_logs'
        verbose_name = _("导入日志")
        verbose_name_plural = _("导入管理")
        indexes = [
            models.Index(fields=['tenant'], name='idx_import_tenant'),
            models.Index(fields=['importer'], name='importers_idx_importer_id'),
            models.Index(fields=['status'], name='importers_idx_status'),
            models.Index(fields=['created_at'], name='importers_idx_created_at'),
        ]

    def __str__(self):
        return self.file_name

    def save(self, *args, **kwargs):
        # 可在此添加逻辑，例如自动计算 fail_count = total_count - success_count
        # 如果你希望自动维护 fail_count，可以取消下面注释
        self.fail_count = self.total_count - self.success_count
        super().save(*args, **kwargs)